var express = require('express');
var router = express.Router();
var Segment = require('node-segment').Segment;
var sql = require('./../sql');
var Pro = require('./../sql/col/pros');

var segment = new Segment();
segment.useDefault();
router.get('/', function(req, res, next) {
  res.send('搜索相关接口');
});

/**
 * @api {get} api/search/fenci 分词-搜索测试
 * @apiDescription 分词-搜索测试
 * @apiGroup search
 * @apiParam { string } value 分词-搜索测试
 * @apiSuccessExample { json } Success-Response:
 * res.send({
    code: '200',
    message: '分词-搜索测试',
    data: data
  });
 * @apiSampleRequest /api/search/fenci
 * @apiVersion 1.0.0
 */
router.get('/fenci', function(req, res, next) {
  var data = segment.doSegment(req.query.value)
  // 数据库操作 --- 返回数据
  res.send({
    code: '200',
    message: '分词-搜索测试',
    data: data
  });
});
/**
 * @api {get} api/search/search 搜索列表
 * @apiDescription 搜索列表
 * @apiGroup search
 * @apiParam { string } value 搜索关键词
 * @apiSuccessExample { json } Success-Response:
 * res.send({
      code: '200',
      message: '搜索列表',
      data
    })
 * @apiSampleRequest /api/search/search
 * @apiVersion 1.0.0
 */
router.get('/search', function(req, res, next) {
  const { value } = req.query
  var reg = new RegExp(value, 'i');
  // $regex用来设置匹配字符串的正则表达式
  var searchObj = [
    { proname: { $regex: reg } },
    { desc: { $regex: reg } }
  ]
  // 或查询
  sql.find(Pro, { $or: searchObj }, { _id: 0 }).then(data => {
    res.send({
      code: '200',
      message: '搜索列表',
      data
    })
  })
});

module.exports = router;
